'use strict';

const moment = require('moment');

module.exports = async (ctx, next) => {
   ctx.fs = ctx.fs || {};
   const { path, header, query } = ctx;
   if (path) {
      try {
         const { Op } = ctx.fs.dc.ORM;
         const tokenFormatRegexp = /^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$/g;
         const token = query.token || header.token;

         if (token && tokenFormatRegexp.test(token)) {
            const existUser = await ctx.fs.models.UserToken.findOne({
               where: {
                  token,
                  expired: {
                     [Op.gt]: moment().format('YYYY-MM-DD HH:mm:ss')
                  }
               }
            });
            if (existUser) {
               ctx.fs.curUser = existUser;
               await next();
            } else {
               ctx.throw(401, 'Unauthorized');
            }
         } else {
            ctx.throw(401, 'Unauthorized');
         }
      } catch (error) {
         ctx.logger.error(error);
         ctx.throw(400, error);
      }
   } else {
      await next();
   }
}
